package com.laysonx.easy.invoke.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description
 * @Author lixin
 * @Date 2018/8/14 15:36
 */
public class TokenUtil {

    /**
     * token 过期时间: 10天
     */
    public static final int calendarField = Calendar.DATE;
    public static final int calendarInterval = 10;
    public static final String TOKEN_SECRET = "S!*$gsMcEu2!w^1W!@Cf";
    public static final String CLAIM_KEY = "EASY_INVOKE_TICKET";


    public static String createToken(Integer field, Integer amount, String claim){
        Date iatDate = new Date();
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(field, amount);
        Date expiresDate = nowTime.getTime();

        // 获取月
        int year = nowTime.get(Calendar.YEAR);
        // 获取月
        int month = nowTime.get(Calendar.MONTH);
        // 获取日
        int date = nowTime.get(Calendar.DATE);

        // header Map
        Map<String, Object> map = new HashMap<>(2);
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        String token = JWT.create().withHeader(map)
                .withClaim(CLAIM_KEY, claim)
                // sign time
                .withIssuedAt(iatDate)
                // expire time
                .withExpiresAt(expiresDate)
                // signature
                .sign(Algorithm.HMAC256(TOKEN_SECRET));

        return token;
    }


    public static String createToken(String claim){
        return TokenUtil.createToken(calendarField, calendarInterval, claim);
    }

    /**
     * 解密Token
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) throws JWTVerificationException {
        DecodedJWT jwt = null;
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TOKEN_SECRET)).build();
        jwt = verifier.verify(token);

        return jwt.getClaims();
    }

    /**
     * 根据Token获取user_id
     *
     * @param token
     * @return user_id
     */
    public static String getTicket(String token) throws JWTVerificationException   {
        Map<String, Claim> claims = verifyToken(token);
        Claim claim = claims.get(CLAIM_KEY);
        if (null == claim || StringUtils.isEmpty(claim)) {
            throw new RuntimeException("Ticket 验证错误");
        }
        return claim.asString();
    }

    public static void main(String[] args) throws Exception {

    }
}
